package com.example.readwrite;

public class ReadWriteLock {

    private int waitingWriter = 0;
    private int waitingReader = 0;
    private int readReader = 0;
    private int writeWriter = 0;

    public synchronized void readLock() {
        try {
            waitingReader++;
            while (writeWriter > 0) {
                this.wait();
            }
            waitingReader--;
            readReader++;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void readUnlock() {
        readReader--;
        notifyAll();
    }

    public synchronized void writeLock() {
        try {
            waitingWriter++;
            while (writeWriter > 0 || readReader > 0) {
                this.wait();
            }
            waitingWriter--;
            writeWriter++;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void writeUnlock() {
        writeWriter--;
        this.notifyAll();
    }

}
